package org.marsdonne.sync.resolver;

import graphql.kickstart.tools.GraphQLQueryResolver;
import org.marsdonne.commons.jpa.FilterSpecSupport;
import org.marsdonne.sync.Record;
import org.marsdonne.sync.RecordFilters;
import org.marsdonne.sync.RecordRepos;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RecordQueryResolver implements GraphQLQueryResolver, FilterSpecSupport<Record> {
    @Resource
    private RecordRepos repos;

    public Iterable<Record> getRecords(RecordFilters filters) {
        Specification<Record> spec = null;

        if (filters != null) {
            if (filters.getDomain() != null)
                spec = by("domain", filters.getDomain());

            if (filters.getAction() != null) {
                Specification<Record> specPart = by("action", filters.getAction());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }

            if (filters.getDateSynced() != null) {
                Specification<Record> specPart = by("dateSynced", filters.getDateSynced());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }
        }

        Sort sort = Sort.by("dateSynced").descending();

        if (spec == null)
            return repos.findAll(sort);
        else
            return repos.findAll(spec, sort);
    }
}
